const dbConfig = require('../util/dbconfig')

// 检查用户是否已关注 
let checkFollow = async (user_id, follow_id) => {
  let sql = 'SELECT * FROM follow WHERE user_id = ? and follow_id = ?';
  let sqlArr = [user_id, follow_id];
  let result = await dbConfig.SySqlConnect(sql, sqlArr);
  if (result.length) {
    return true;
  } else {
    return false;
  }
}

// 关注接口
follow = async (req, res) => {
  let { user_id, follow_id } = req.body;
  // 检查用户是否已关注
  if (!await checkFollow(user_id, follow_id)) {
    if (user_id == follow_id) {
      res.send({
        code: 400,
        msg: '不能关注自己'
      })
    } else {
      let sql = 'INSERT INTO follow (user_id, follow_id) VALUES(?, ?)';
      let sqlArr = [user_id, follow_id];
      let result = await dbConfig.SySqlConnect(sql, sqlArr);
      if (result.affectedRows == 1) {
        res.send({
          code: 200,
          msg: '关注成功'
        })
      } else {
        res.send({
          code: 400,
          msg: '关注失败'
        })
      }
    }
  } else {
    res.send({
      code: 400,
      msg: '已关注,不能重复关注'
    })
  }
}

module.exports = {
  follow,
}